<template>
  <Header title="申请退款" :hasRight="true" @save="saveRefund" />

  <div class="refund">
    <div class="orderBox">
      <OrderItem
        v-for="(orderItem, orderItemIndex) in orderData.orderItems"
        :key="orderItemIndex"
        :orderItem="orderItem"
      />
    </div>
    <div class="form">
      <nut-form :model-value="formData" :rules="formRules" ref="ruleForm">
        <nut-form-item label="支付金额" body-align="right">
          <nut-price :price="orderData.payAmount" size="normal" symbol="¥" />
        </nut-form-item>
        <nut-form-item label="退款金额" body-align="right">
          <nut-price :price="orderData.payAmount" size="normal" symbol="¥" />
        </nut-form-item>
        <nut-form-item label="退款原因" prop="reason">
          <nut-textarea
            placeholder="请填写退款原因"
            v-model="formData.reason"
            :rows="5"
            limit-show
            max-length="100"
          />
        </nut-form-item>
      </nut-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 表单数据
const ruleForm = ref(null);
const formData = reactive({
  reason: "",
});
const formRules = reactive({
  reason: [{ required: true, message: "请填写退款原因" }],
});

// 订单数据
const orderData = reactive({
  orderItems: [],
});

// 重复提交token
const repeatSubmitToken = ref(null);
const getRepeatSubmitToken = () => {
  proxy.$thirdApi.common
    .repeatSubmitToken()
    .then((res) => {
      repeatSubmitToken.value = res.data;
    })
    .catch((error) => {});
};

// 申请退款
const saveRefund = () => {
  ruleForm.value.validate().then(({ valid, errors }) => {
    if (valid) {
      proxy.$orderApi.refund
        .applyRefund({
          repeatSubmitToken: repeatSubmitToken.value,
          orderId: route.query.orderId,
          reason: formData.reason,
        })
        .then((res) => {
          router.back();
        });
    }
  });
};

// 页面加载完成
onMounted(() => {
  getRepeatSubmitToken();
  proxy.$orderApi.order
    .info(route.query.orderId)
    .then((res) => {
      Object.assign(orderData, res.data);
    })
    .catch((error) => {});
});
</script>

<style lang="less" scoped>
.refund {
  margin: 5px;
  .orderBox {
    padding: 10px;
    background: #fff;
    border-radius: 5px;
    .orderItem {
      margin-bottom: 15px;
    }
    .orderItem:last-child {
      margin-bottom: 0px;
    }
  }
}
</style>